import requests
import cv2
import os
from datetime import datetime

# 设置 API 地址
fetch_api_url = "http://192.168.153.130/api/explore.php?type=videonook"
post_api_url = "http://192.168.153.130/api/explore.php?type=videcgok"

def get_api_data(url):
    response = requests.get(url)
    print("get video API响应状态码:", response.status_code)
    #print("get video API响应内容:", response.text)
    if response.status_code == 200:
        try:
            data = response.json()
            if not data:
                print("API返回的数据为空，不执行后续操作")
                return None
            return data
        except requests.exceptions.JSONDecodeError as e:
            #print("JSON解码错误:", e)
            return None
    else:
        print("获取API数据失败，状态码:", response.status_code)
        return None

def send_result_to_php(nid, isok, filesrc):
    # 确保 filesrc 使用 / 开头的绝对路径
    if filesrc.startswith("../"):
        filesrc = filesrc.replace("../", "/")
    elif filesrc.startswith("./"):
        filesrc = filesrc.replace("./", "/")
    data = {
        'nid': nid,
        'isok': isok,
        'filesrc': filesrc
    }
    response = requests.post(post_api_url, data=data)
    if response.status_code == 200:
        print("结果已成功发送到PHP API")
    else:
        print("发送结果到PHP API失败")

def extract_frame(video_path, output_path, nid):
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        print(f"无法打开视频文件: {video_path}")
        send_result_to_php(nid, "2", f"{output_path},{video_path}")
        return

    frame_index = 0
    success = False

    while cap.isOpened() and frame_index < 100:
        cap.set(cv2.CAP_PROP_POS_FRAMES, frame_index)
        ret, frame = cap.read()
        if not ret:
            break
        if cv2.countNonZero(cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)) > 0:
            cv2.imwrite(output_path, frame)
            print(f"已保存非黑色帧到 {output_path}")
            send_result_to_php(nid, "1", f"{output_path},{video_path}")
            success = True
            break
        frame_index += 1

    if not success:
        print(f"未在 {video_path} 中找到非黑色帧")
        send_result_to_php(nid, "2", f"{output_path},{video_path}")
    cap.release()

def main():
    data = get_api_data(fetch_api_url)
    if data:
        today_date = datetime.now().strftime("%Y%m%d")
        save_dir = f"../data/{today_date}"
        os.makedirs(save_dir, exist_ok=True)

        for item in data:
            video_src = item['video_src'].replace("\\", "/")
            nid = item['note_id']
            output_path = os.path.join(save_dir, os.path.basename(video_src).replace(".mp4", ".jpg")).replace("\\", "/")
            video_path = os.path.join("..", video_src.lstrip("/")).replace("\\", "/")

            print(f"正在处理的视频路径: {video_path}")
            extract_frame(video_path, output_path, nid)
    else:
        print("无数据可处理")

if __name__ == "__main__":
    main()
